rm(list = ls())

if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, rdrobust)

# Load and prepare data
civey <- readRDS("data/civey_data_clean.rds") %>%
    filter(!is.na(yob), yob > 1945) %>%
    dplyr::select(yob, east_bin, male_bin, gdr_dictatorship_bin) %>%
    mutate(
        post = ifelse(yob > 1970, 1, 0),
        gender = ifelse(male_bin == 1, "Men", "Women"),
        post_gender = paste(post, gender, sep = "_"),
        east_bin = ifelse(east_bin == 1, "East Germany", "West Germany")
    ) %>%
    filter(between(yob, 1971 - 4, 1971 + 5))

# Calculate summary statistics
plot_df_sum <- civey %>%
    group_by(gender, post_gender, east_bin, yob) %>%
    summarise(m = mean(gdr_dictatorship_bin, na.rm = T), .groups = "drop")

# Create plot
p <- ggplot(
    civey,
    aes(x = yob, y = gdr_dictatorship_bin, col = gender, group = post_gender)
) +
    geom_smooth(method = "lm") +
    geom_point(data = plot_df_sum, aes(x = yob, y = m, color = gender)) +
    geom_vline(xintercept = 1970.5, linetype = "dotted") +
    scale_color_manual(values = c("black", "grey")) +
    theme_bw() +
    labs(
        col = "",
        x = "",
        y = "Mean of: GDR was a dictatorship"
    ) +
    facet_grid(gender ~ east_bin, scales = "free_y") +
    scale_x_continuous(breaks = 1960:1980) +
    theme(
        legend.position = "none",
        axis.title.x = element_blank()
    )

p
